import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, CarOutlined, ToolOutlined, CheckOutlined, CloseOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Modal, Form, Input, InputNumber, Select, DatePicker, message, Tabs, Tag, Descriptions } from '@/utils/antd-imports';

import { vehicleApi } from '../../api/vehicleApi';
import dayjs from 'dayjs';

const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

export default function VehicleManagement() {
  const [loading, setLoading] = useState(false);
  const [vehicleList, setVehicleList] = useState([]);
  const [applications, setApplications] = useState([]);
  const [maintenanceRecords, setMaintenanceRecords] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [applicationModalVisible, setApplicationModalVisible] = useState(false);
  const [maintenanceModalVisible, setMaintenanceModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [selectedVehicle, setSelectedVehicle] = useState(null);
  const [form] = Form.useForm();
  const [applicationForm] = Form.useForm();
  const [maintenanceForm] = Form.useForm();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [vehiclesResponse, applicationsResponse] = await Promise.all([
        vehicleApi.getVehicleList(),
        vehicleApi.getVehicleApplications()
      ]);
      setVehicleList(vehiclesResponse.data);
      setApplications(applicationsResponse.data);
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAddVehicle = () => {
    setEditingRecord(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEditVehicle = (record) => {
    setEditingRecord(record);
    form.setFieldsValue({
      ...record,
      purchaseDate: record.purchaseDate ? dayjs(record.purchaseDate) : null,
    });
    setModalVisible(true);
  };

  const handleDeleteVehicle = async (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这辆车吗？',
      onOk: async () => {
        try {
          await vehicleApi.deleteVehicle(id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmitVehicle = async (values) => {
    try {
      const data = {
        ...values,
        purchaseDate: values.purchaseDate ? values.purchaseDate.format('YYYY-MM-DD') : null,
      };

      if (editingRecord) {
        await vehicleApi.updateVehicle(editingRecord.id, data);
        message.success('更新成功');
      } else {
        await vehicleApi.createVehicle(data);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchData();
    } catch (error) {
      message.error(editingRecord ? '更新失败' : '创建失败');
    }
  };

  const handleApplyVehicle = (vehicleId) => {
    setSelectedVehicle(vehicleId);
    applicationForm.resetFields();
    setApplicationModalVisible(true);
  };

  const handleSubmitApplication = async (values) => {
    try {
      await vehicleApi.applyVehicle({
        vehicleId: selectedVehicle,
        ...values,
        startDate: values.startDate.format('YYYY-MM-DD'),
        endDate: values.endDate.format('YYYY-MM-DD'),
      });
      message.success('申请成功');
      setApplicationModalVisible(false);
      fetchData();
    } catch (error) {
      message.error('申请失败');
    }
  };

  const handleApproveApplication = async (id) => {
    try {
      await vehicleApi.approveVehicleApplication(id, { remark: '审批通过' });
      message.success('审批成功');
      fetchData();
    } catch (error) {
      message.error('审批失败');
    }
  };

  const handleRejectApplication = async (id) => {
    try {
      await vehicleApi.rejectVehicleApplication(id, { remark: '审批拒绝' });
      message.success('拒绝成功');
      fetchData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleAddMaintenance = (vehicleId) => {
    setSelectedVehicle(vehicleId);
    maintenanceForm.resetFields();
    setMaintenanceModalVisible(true);
  };

  const handleSubmitMaintenance = async (values) => {
    try {
      await vehicleApi.addMaintenanceRecord(selectedVehicle, {
        ...values,
        maintenanceDate: values.maintenanceDate.format('YYYY-MM-DD'),
      });
      message.success('添加成功');
      setMaintenanceModalVisible(false);
      fetchMaintenanceRecords(selectedVehicle);
    } catch (error) {
      message.error('添加失败');
    }
  };

  const fetchMaintenanceRecords = async (vehicleId) => {
    try {
      const response = await vehicleApi.getVehicleMaintenance(vehicleId);
      setMaintenanceRecords(response.data);
    } catch (error) {
      message.error('获取维修记录失败');
    }
  };

  const vehicleColumns = [
    {
      title: '车牌号',
      dataIndex: 'plateNumber',
      key: 'plateNumber',
    },
    {
      title: '车型',
      dataIndex: 'model',
      key: 'model',
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      key: 'brand',
    },
    {
      title: '购买日期',
      dataIndex: 'purchaseDate',
      key: 'purchaseDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          available: { color: 'green', text: '可用' },
          in_use: { color: 'blue', text: '使用中' },
          maintenance: { color: 'orange', text: '维修中' },
          scrapped: { color: 'red', text: '已报废' },
        };
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EyeOutlined />} size="small">
            查看
          </Button>
          <Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEditVehicle(record)}>
            编辑
          </Button>
          <Button type="link" icon={<CarOutlined />} size="small" onClick={() => handleApplyVehicle(record.id)}>
            申请使用
          </Button>
          <Button type="link" icon={<ToolOutlined />} size="small" onClick={() => handleAddMaintenance(record.id)}>
            维修记录
          </Button>
          <Button type="link" icon={<DeleteOutlined />} size="small" danger onClick={() => handleDeleteVehicle(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const applicationColumns = [
    {
      title: '申请单号',
      dataIndex: 'applicationNo',
      key: 'applicationNo',
    },
    {
      title: '申请人',
      dataIndex: 'applicant',
      key: 'applicant',
    },
    {
      title: '车牌号',
      dataIndex: 'plateNumber',
      key: 'plateNumber',
    },
    {
      title: '使用日期',
      dataIndex: 'startDate',
      key: 'startDate',
    },
    {
      title: '归还日期',
      dataIndex: 'endDate',
      key: 'endDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          pending: { color: 'orange', text: '待审批' },
          approved: { color: 'green', text: '已通过' },
          rejected: { color: 'red', text: '已拒绝' },
          in_use: { color: 'blue', text: '使用中' },
          returned: { color: 'gray', text: '已归还' },
        };
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          {record.status === 'pending' && (
            <>
              <Button type="link" icon={<CheckOutlined />} size="small" onClick={() => handleApproveApplication(record.id)}>
                通过
              </Button>
              <Button type="link" icon={<CloseOutlined />} size="small" danger onClick={() => handleRejectApplication(record.id)}>
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <Tabs defaultActiveKey="vehicles">
          <TabPane tab="车辆管理" key="vehicles">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAddVehicle}>
                  新增车辆
                </Button>
              </Space>
            </div>

            <Table
              columns={vehicleColumns}
              dataSource={vehicleList}
              loading={loading}
              rowKey="id"
              pagination={{
                total: vehicleList.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </TabPane>

          <TabPane tab="用车申请" key="applications">
            <Table
              columns={applicationColumns}
              dataSource={applications}
              loading={loading}
              rowKey="id"
              pagination={{
                total: applications.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={editingRecord ? '编辑车辆' : '新增车辆'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmitVehicle}
        >
          <Form.Item
            name="plateNumber"
            label="车牌号"
            rules={[{ required: true, message: '请输入车牌号' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="brand"
            label="品牌"
            rules={[{ required: true, message: '请输入品牌' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="model"
            label="车型"
            rules={[{ required: true, message: '请输入车型' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="purchaseDate"
            label="购买日期"
            rules={[{ required: true, message: '请选择购买日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="available">可用</Option>
              <Option value="in_use">使用中</Option>
              <Option value="maintenance">维修中</Option>
              <Option value="scrapped">已报废</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="申请用车"
        open={applicationModalVisible}
        onCancel={() => setApplicationModalVisible(false)}
        onOk={() => applicationForm.submit()}
        width={600}
      >
        <Form
          form={applicationForm}
          layout="vertical"
          onFinish={handleSubmitApplication}
        >
          <Form.Item
            name="purpose"
            label="用车目的"
            rules={[{ required: true, message: '请输入用车目的' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="destination"
            label="目的地"
            rules={[{ required: true, message: '请输入目的地' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="startDate"
            label="开始日期"
            rules={[{ required: true, message: '请选择开始日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="endDate"
            label="结束日期"
            rules={[{ required: true, message: '请选择结束日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="remark"
            label="备注"
          >
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="维修记录"
        open={maintenanceModalVisible}
        onCancel={() => setMaintenanceModalVisible(false)}
        onOk={() => maintenanceForm.submit()}
        width={600}
      >
        <Form
          form={maintenanceForm}
          layout="vertical"
          onFinish={handleSubmitMaintenance}
        >
          <Form.Item
            name="maintenanceDate"
            label="维修日期"
            rules={[{ required: true, message: '请选择维修日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="maintenanceType"
            label="维修类型"
            rules={[{ required: true, message: '请选择维修类型' }]}
          >
            <Select>
              <Option value="routine">常规保养</Option>
              <Option value="repair">故障维修</Option>
              <Option value="inspection">安全检查</Option>
              <Option value="other">其他</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="维修描述"
            rules={[{ required: true, message: '请输入维修描述' }]}
          >
            <TextArea rows={4} />
          </Form.Item>

          <Form.Item
            name="cost"
            label="维修费用"
          >
            <InputNumber
              style={{ width: '100%' }}
              formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={value => value.replace(/¥\s?|(,*)/g, '')}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
